package com.example.demo_mysql_mybatisplus.util.easyexcel.exports.customized.dynamic.column;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Getter;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 实现动态的表头/列 ：根据指定的顺序进行导出
* */
@Getter
public class DataSorter <T> {
    List<List<String>> heads = new LinkedList<>();
    List<List> datas = new LinkedList<>();

    /** 通过指定顺序的字段名集合，使用反射获取对应的字段值 放到 二维集合中 */
    public DataSorter(List<String> fieldsInSpecifiedOrder ,List<T> dataList ,Class<T> dtoClass ) {
        // 先获取两个集合
        Field[] declaredFields = dtoClass.getDeclaredFields() ;
        Set<String> declaredFieldSet = new HashSet<>(declaredFields.length); //集合 1
        Map<String ,String[]> fieldMapAnnotation = new HashMap<>(declaredFields.length); //集合 2
        ExcelProperty annotation = null;
        for (Field declaredField : declaredFields ) {
            declaredFieldSet.add(declaredField.getName());
            annotation = declaredField.getAnnotation(ExcelProperty.class);
            if(annotation!=null){
                fieldMapAnnotation.put(declaredField.getName(),annotation.value());
            }else{
                String[] arr = {declaredField.getName()};
                fieldMapAnnotation.put(declaredField.getName(), arr);
            }
        }
        // 处理表头字段
        fieldsInSpecifiedOrder.forEach(fieldName->{
            if(null!=fieldMapAnnotation.get(fieldName)){
                heads.add(Arrays.asList(fieldMapAnnotation.get(fieldName)));
            }
        });
        // 处理内容数据
        if (CollUtil.isNotEmpty(dataList)) {
            dataList.forEach(data->{
                List list = new LinkedList();
                fieldsInSpecifiedOrder.forEach(fieldName->{
                    if(declaredFieldSet.contains(fieldName)){
                        list.add( ReflectUtil.getFieldValue(data , fieldName) ); // https://blog.csdn.net/weixin_70221917/article/details/129132630
                    }
                });
                datas.add(list);
            });
        }
    }

}
